package com.yan_jiu_sheng.LeetCodeHot100.AC;

/**
 * https://leetcode.cn/problems/palindrome-linked-list/description/?envType=study-plan-v2&envId=top-100-liked
 * 通过
 *
 * @author yulongTian
 * @create 2024-05-29 15:17
 */
public class Test24 {
    public static void main(String[] args) {

    }

    private class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
            next = null;
        }
    }

    public boolean isPalindrome(ListNode head) {
        if (head == null || head.next == null) {
            return true;
        }
        int listLen = 0;
        ListNode pointer = head;
        ListNode head2 = null;
        while (pointer != null) {
            listLen++;
            pointer = pointer.next;
        }
        pointer = head;
        int i = 0;
        while (pointer != null) {
            ListNode temp = pointer;
            pointer = pointer.next;
            temp.next = head2;
            head2 = temp;
            i++;
            if (listLen % 2 == 0) {
                if (i == listLen / 2) {
                    head = pointer;
                    break;
                }
            } else {
                if (i == listLen / 2) {
                    head = pointer;
                    ListNode newNode = new ListNode(pointer.val);
                    newNode.next = head2;
                    head2 = newNode;
                    break;
                }
            }
        }
        while (head != null) {
            if (head.val != head2.val) {
                return false;
            }
            head = head.next;
            head2 = head2.next;
        }
        return true;
    }

}
